<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" href="/favicon.ico">
    <link rel="stylesheet" href="/resources/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="/resources/css/public.css" media="all" />
    <link rel="stylesheet" href="/resources/layui_ext/dtree/dtree.css" media="all" />
    <link rel="stylesheet" href="/resources/layui_ext/dtree/font/dtreefont.css" media="all" />
</head>
<body class="childrenBody">
<!-- 查询条件开始-->
<form class="layui-form">
    <blockquote class="layui-elem-quote quoteBox">
        <form class="layui-form" id="searchForm">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">用户名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="loginname" id="search_loginName" class="layui-input searchVal" placeholder="请输入用户名称" />
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">真实名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" id="search_name" class="layui-input searchVal" placeholder="请输入真实名称" />
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">开始时间</label>
                    <div class="layui-input-inline">
                        <input type="text" name="startTime" id="startTime" class="layui-input searchVal" readonly placeholder="开始时间" />
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">结束时间</label>
                    <div class="layui-input-inline">
                        <input type="text" name="endTime" id="endTime" class="layui-input searchVal" readonly placeholder="结束时间" />
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block" style="text-align: center;">
                    <button type="button" class="layui-btn" lay-submit lay-filter="doSearch">
                        <span class="layui-icon layui-icon-search"></span>查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-warm" id="resetSearch">
                        <span class="layui-icon layui-icon-refresh-1"></span>重置
                    </button>
                </div>
            </div>
        </form>
    </blockquote>
</form>
<!-- 查询条件结束-->


<!-- 数据表格开始 -->
<div>
    <table class="layui-hide" id="userTable" lay-filter="userTable"></table>
    <!-- 工具栏 -->
    <div id="userToolBar" style="display: none;">
        <button type="button" lay-event="add" class="layui-btn layui-btn-sm" ><span class="layui-icon layui-icon-add-1"></span>添加用户</button>
    </div>

    <div id="userRowBar" style="display: none;">
        <button type="button" lay-event="update" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-edit"></span>更新
        </button>
        <button type="button" lay-event="delete" class="layui-btn layui-btn-sm layui-btn-danger">
            <span class="layui-icon layui-icon-delete"></span>删除
        </button>
        <button type="button" lay-event="resetPwd" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-refresh"></span>重置密码
        </button>
        <button type="button" lay-event="selectRole" class="layui-btn layui-btn-sm layui-btn-warm">
            <span class="layui-icon layui-icon-edit"></span>分配角色
        </button>
    </div>
</div>
<!-- 数据表格结束 -->

<!-- 添加和修改的弹出层开始 -->

<div  style="display: none;padding: 5px" id="addOrUpdateDiv">
    <form class="layui-form" style="width:90%;" id="dataFrm" lay-filter="dataFrm">
        <!-- 隐藏域，保存用户id -->
        <input type="hidden" name="id" id="id">
        <div class="layui-form-item">
            <label class="layui-form-label">所属部门</label>
            <div class="layui-input-block">
                <!-- 隐藏域：保存选中部门的节点id -->
                <input type="hidden" name="deptid" id="deptid">
                <ul id="deptTree" class="dtree" data-id="0"></ul>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">领导部门</label>
            <div class="layui-input-block">
                <ul id="mgrTree" class="dtree" data-id="0"></ul>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">直属领导</label>
            <div class="layui-input-block">
                <select name="mgr" id="mgr">
                    <option value="0">请选择直属领导</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" id="name" lay-verify="required" autocomplete="off" placeholder="请输入用户姓名" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">登陆名称</label>
                <div class="layui-input-block">
                    <input type="text" name="loginname" id="loginname" lay-verify="required"  autocomplete="off" placeholder="请输入登陆名称" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户地址</label>
            <div class="layui-input-block">
                <input type="text" name="address" lay-verify="required" autocomplete="off" placeholder="请输入用户地址" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户备注</label>
            <div class="layui-input-block">
                <textarea class="layui-textarea" name="remark" id="content"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户性别</label>
                <div class="layui-input-block">
                    <input type="radio" name="sex" value="1" title="男" checked="">
                    <input type="radio" name="sex" value="0" title="女" >
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">是否可用</label>
                <div class="layui-input-block">
                    <input type="radio" name="available" value="1" title="是" checked="">
                    <input type="radio" name="available" value="0" title="否" >
                </div>
            </div>
        </div>

        <div class="layui-form-item layui-row layui-col-xs12">
            <div class="layui-input-block" style="text-align: center;">
                <button type="button" class="layui-btn" lay-submit lay-filter="doSubmit"><span class="layui-icon layui-icon-add-1"></span>提交</button>
                <button type="button" class="layui-btn layui-btn-warm" ><span class="layui-icon layui-icon-refresh-1"></span>重置</button>
            </div>
        </div>
    </form>
</div>

<!-- 添加和修改的弹出层结束 -->

<!-- 用户分配角色弹出层  开始 -->
<div style="display: none;padding: 5px" id="selectUserRoleDiv">
    <table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
</div>
<!-- 用户分配角色弹出层  结束 -->



<script type="text/javascript" src="/resources/layui/layui.js"></script>
<script type="text/javascript">

    var tableIns;
    layui.extend({
        dtree: '/resources/layui_ext/dtree/dtree'   // {/}的意思即代表采用自有路径，即不跟随 base 路径
    }).use(['jquery','form','table','layer','dtree','laydate'],function () {
        var $=layui.jquery;
        var form=layui.form;
        var table=layui.table;
        var layer=layui.layer;
        var dtree = layui.dtree;
        var laydate = layui.laydate;
        //初始化时间选择器
        laydate.render({
            elem:'#startTime',//绑定渲染的元素
            type:'datetime'//控件选择类型
        });
        laydate.render({
            elem:'#endTime',//绑定渲染的元素
            type:'datetime'//控件选择类型
        });

        //表格渲染
        tableIns=table.render({
            elem: '#userTable'
            ,url:'/sys/user/list'
            ,toolbar: '#userToolBar' //开启头部工具栏，并为其绑定左侧模板
            ,page: true
            ,title: '用户数据表'
            ,cols: [  [
                {type:'checkbox'}
                ,{field:'id',title:'用户编号',align:'center'}
                ,{field:'loginname',title:'用户名称',align:'center'}
                ,{field:'name',title:'真实姓名',align:'center'}
                ,{field:'sex',title:'性别',align:'center',templet:function (d) {
                        return d.open==1?"<font color='blue'>男</font>":"<font color='red'>女</font>";
                    }}
                ,{field:'deptName',title:'部门名称',align:'center'}
                ,{field:'mgrName',title:'直属领导',align:'center'}
                ,{field:'hiredate',title:'入职时间',align:'center'}
                ,{title:'操作',toolbar:'#userRowBar',width:400,fixed:'right'}
            ]  ],
            done:function (res,curr,count) {
                //判断当前页面是否大于1并且当前页的数据为0
                if (curr>1&&res.data.length==0){
                    var pageValue=curr-1
                    //刷新数据表格
                    tableIns.reload({
                        page:{curr:pageValue}
                    });
                }
            }
        });

        //监听表单提交事件
        form.on("submit(doSearch)",function (data) {
            tableIns.reload({
                url:'/sys/user/list',
                where:data.field,
                page:{
                    curr:1
                }
            });
            return false;
        });

        //监听表格头工具栏事件
        table.on("toolbar(userTable)",function (obj) {
            switch (obj.event) {
                case "add":
                    //打开添加用户窗口
                    openAddUserWindow();
                    break;
            }
        });

        //监听表格头工具栏事件
        table.on("tool(userTable)",function (obj) {
            switch (obj.event) {
                case "update":
                    //打开修改用户窗口
                    openUpdateUserWindow(obj.data);
                    break;
                case "delete":
                    //删除
                    deleteInfo(obj.data);
                    break;
                case "selectRole"://分配角色
                    //分配角色
                    AssigningRole(obj.data);
                    break;
            }
        });

        var mainIndex;//打开窗口的索引
        var url;//提交请求地址

        /**
         * 打开添加部门的方法
         */
        function openAddUserWindow() {
            mainIndex =layer.open({
                type:1,
                content:$("#addOrUpdateDiv"),
                area:["800px","550px"],
                title:"添加用户",
                success:function () {
                    //每次打开窗口，清空表单数据
                    $("#dataFrm")[0].reset();
                    //提交请求
                    url = "/sys/user/addUser";
                    //移除只读属性
                    $("#loginname").removeAttr("readonly");
                }
            });
        }

        /**
         * 打开修改部门的方法
         */
        function openUpdateUserWindow(data) {
            mainIndex =layer.open({
                type:1,
                content:$("#addOrUpdateDiv"),
                area:["800px","550px"],
                title:"修改用户",
                success:function () {
                    //登录名称设置只读
                    $("#loginname").attr("readonly","readonly");
                    //解绑失去焦点事件,毕竟修改用户功能用户名名称是不能给修改的，还有不用再取消弹出验证是否存在用户名信息
                    $("#loginname").unbind();
                    //表单数据回显，打开后回显显示信息
                    form.val("dataFrm",data);
                    //下拉菜单树回显,所属部门回显
                    dtree.dataInit("deptTree",data.deptid);
                    //设置显示的值 要设置这个属性selectVal才能显示里面的值
                    dtree.selectVal("deptTree");
                    //设置所属领导部门回显
                    //获取所属领导的ID
                    var mgrId=data.mgr;
                    //根据领导ID查询该领导所在的部门
                    $.get("/sys/user/loadUserById", {"id":mgrId}, function (result) {
                        //当前行的数据
                        var d=result.data;
                        //下拉菜单树回显
                        dtree.dataInit("mgrTree",d.deptid);
                        //设置显示的值
                        dtree.selectVal("mgrTree");
                        //根据部门ID查询该部门下的员工列表
                            $.get("/sys/user/loadUserByDeptId",{"deptid":d.deptid},function(result){
                            //获取返回的数据
                            var userList = result.data;
                            var html ="<option value=''>请选择所属领导</option>"
                            for (var i = 0; i < userList.length; i++) {
                                html +="<option value='"+userList[i].id+"'>"+userList[i].name+"</option>"
                            }
                            //将网页追加到下拉列表中
                            $("#mgr").html(html);
                            //直属领导回显
                            $("#mgr").val(mgrId);
                            //重新渲染select
                            form.render("select");
                        },"json");
                    }, "json");

                    //提交请求
                    url = "/sys/user/updateUser";
                }
            });
        }


        //初始化下拉菜单树
        //页面初始化时加载部门列表
        var deptSelectTree = dtree.renderSelect({
            elem: "#deptTree",
            width: "100%", // 指定树的宽度
            url: "/sys/dept/loadDeptTreeLeft", // 使用url加载（可与data加载同时存在）
            dataStyle: "layuiStyle",  //使用layui风格的数据格式
            dataFormat: "list",  //配置data的风格为list
            response:{message:"msg",statusCode:0},  //修改response中返回数据的定义
        });

        //监听树节点的点击事件
        dtree.on("node('deptTree')" ,function(obj){
            //选中所属部门后，将该部门的ID放到隐藏域中
            $("#deptid").val(obj.param.nodeId);
        });

        //领导部门下拉菜单数据
        //页面初始化时加载部门列表
        var deptSelectTree = dtree.renderSelect({
            elem: "#mgrTree",
            width: "100%", // 指定树的宽度
            url: "/sys/dept/loadDeptTreeLeft", // 使用url加载（可与data加载同时存在）
            dataStyle: "layuiStyle",  //使用layui风格的数据格式
            dataFormat: "list",  //配置data的风格为list
            response:{message:"msg",statusCode:0},  //修改response中返回数据的定义
        });

        //监听树节点的点击事件
        dtree.on("node('mgrTree')" ,function(obj){
            //获取选中部门ID
            var deptId=obj.param.nodeId;
            $.get("/sys/user/loadUserByDeptId",{"deptid":deptId},function (result) {
                //获取返回的数据
                var userList = result.data;//data是DateGindViewResult中的date来的
                var html ="<option value=''>请选择所属领导</option>"
                for (var i = 0; i <userList.length; i++) {
                    html +="<option value='"+userList[i].id+"'>"+userList[i].name+"</option>"
                }
                //将网页追加到下拉列表中
                $("#mgr").html(html);
                //重新渲染select
                form.render("select");
            }, "json");

        });


        /**
         * 验证用户是否存在
         *
         */
            //验证用户名是否存在
        var isExist = false;
        //绑定失去焦点事件
        $("#loginname").bind("blur",function () {
            //获取用户名
            var loginname = $(this).val().trim();
            if(loginname.length==0){
                layer.msg("登录名称不能为空！");
            }else {
                $.get("/sys/user/checkLoginName",{"loginname":loginname},function(result){
                    if(result.exist){
                        isExist = true;//存在
                    }else{
                        isExist = false;//不存在
                    }
                    layer.msg(result.message);
                },"json");
            }
        });


        //监听表单提交事件
        form.on("submit(doSubmit)",function (data) {
            $.post(url,data.field,function(result){
                if(result.success){
                    //提示信息
                    layer.msg(result.message,{icon:1});
                    //刷新数据表格
                    tableIns.reload();
                    //刷新下拉菜单树
                    deptSelectTree.reload();
                    //刷新部门管理的左侧菜单树
                    window.parent.left.reload();
                    //关闭当前窗口
                    layer.close(mainIndex);
                }else{
                    //提示信息
                    layer.msg(result.message,{icon:2});
                }
            },"json");
            //禁止页面跳转
            return false;
        });



        /**
         * 删除
         */
        function deleteInfo(data){
            layer.confirm('确定要删除该数据？', {"icon":3,"title":"提示"},function (index) {
                $.post("/sys/user/deleteById", {"id":data.id}, function (result) {
                    console.log(result);
                    if (result.success){
                        tableIns.reload();//表格重新加载
                    }
                    layer.msg(result.message);
                }, "json");
                layer.close(index);
            });
        }

        /**
         * 用户管理分配角色
         */
        function AssigningRole(data) {
            mainIndex = layer.open({
                type: 1,
                content: $("#selectUserRoleDiv"),
                area: ["800px", "550px"],
                title: "分配[" + data.name + "]角色",
                btn: ['<span class="layui-icon layui-icon-ok"></span>确认', '<span class="layui-icon layui-icon-close"></span>取消'],
                yes: function(index, layero){
                    //获取当前选中行
                    var checkStatus = table.checkStatus("roleTable");
                    //判断是否有选中行
                    if(checkStatus.data.length>0){
                        var idArr = [];
                        //循环
                        for (var i = 0; i < checkStatus.data.length; i++) {
                            idArr.push(checkStatus.data[i].id);//获取选中行的id
                        }
                        //转成字符串
                        var ids = idArr.join(",");
                        $.post("/sys/user/saveUserRole",{"userId":data.id,"roleIds":ids},function(result){
                            layer.msg(result.message);
                        },"json");
                        //关闭窗口
                        layer.close(mainIndex);
                    }else{
                        layer.msg("请选择要分配的角色！");
                    }
                },
                btn2: function(index, layero){
                    //按钮【按钮二】的回调

                    //return false 开启该代码可禁止点击该按钮关闭
                },
                success: function () {
                    //初始化角色数据
                    initRoleList(data);
                }
            })
        }

        var roleTableIns;
        //初始化角色列表
        function initRoleList(data) {
            roleTableIns = table.render({
                elem:"#roleTable"
                ,where:{
                    id:data.id //用户ID
                }
                ,url:'/sys/user/initRoleListByUserId'
                ,cols: [ [
                    {type:'checkbox'}
                    ,{field:'id', title:'角色编号', align: 'center'}
                    ,{field:'rolecode', title:'角色编码', align: 'center'}
                    ,{field:'rolename', title:'角色名称', align: 'center'}
                    ,{field:'remark', title:'备注', align: 'center'}
                ] ]
            });
        }

    });

    /**
     * 根据部门ID点击后加载用户列表
     * @param deptId
     */
    function loadTableData(deptId){
        tableIns.reload({
            where:{"deptid":deptId},
            page:{
                curr:1
            }
        });//重载表格刷新
    }
</script>
</body>
</html>